<template>
  <Container>
    <!-- 顶部导航 -->
    <div>
      <el-segmented
        v-model="value"
        :options="options"
        style="width: 100%; height: 10vh;"
        @change="handleValueChange"
      >
        <template #default="{ item }">
          <div class="flex flex-col items-center gap-2 p-2">
            <el-icon size="20">
              <component :is="item.icon" />
            </el-icon>
            <div>{{ item.label }}</div>
          </div>
        </template>
      </el-segmented>
    </div>

    <!-- 消息展示区 -->
    <el-scrollbar class="message-container">
      <el-card
        v-for="message in formattedMessages"
        :key="message.id"
        class="message-card"
        :class="{ unread: !message.isRead }"
        @dblclick="handleClick()"
      > <!-- 动态添加未读样式 -->
        <div>{{ message.content }}</div>
        <el-button
          v-if="!message.isRead"
          type="text"
          size="small"
          @click="markAsRead(message.id)"
        >
          标记为已读
        </el-button>
      </el-card>
    </el-scrollbar>

    <el-pagination
      @current-change="handlePageChange"
      :current-page="currentPage[currentIndex]"
      :page-size="pageSize[currentIndex]"
      layout="prev, pager, next"
      :total="total[currentIndex]"
      class="pagination"
    />

    <Footmenu />
  </Container>
</template>

<script>
import Container from '../components/main/container.vue';
import Footmenu from '../components/main/footmenu.vue';
import { ref, computed, onMounted } from 'vue';
import { Apple, Cherry, Grape, Orange } from '@element-plus/icons-vue';
import { get, post } from "@/net";
import { useRouter } from 'vue-router';

export default {
  name: 'Message',
  components: {
    Container,
    Footmenu,
  },
  setup () {
    // 当前选择的导航项
    const value = ref('点赞信息');

    // 导航选项
    const options = [
      { label: '点赞信息', value: '点赞信息', icon: Apple },
      { label: '提问信息', value: '提问信息', icon: Cherry },
      { label: '回复信息', value: '回复信息', icon: Grape },
      { label: '提问箱信息', value: '提问箱信息', icon: Orange },
    ];

    // 选项与索引的映射表
    const optionsMap = {
      '点赞信息': 0,
      '提问信息': 1,
      '回复信息': 2,
      '提问箱信息': 3,
    };


    const currentPage = ref([1, 1, 1, 1]);
    const pageSize = ref([10, 10, 10, 10]);
    const total = ref([0, 0, 0, 0]);
    const likeMessages = ref([]);
    const questionBoxMessages = ref([]);
    const replyMessages = ref([]);
    const boxMessages = ref([]);

    // 当前选项对应的索引
    const currentIndex = computed(() => {
      const index = optionsMap[value.value];
      return index !== undefined ? index : 0; // 如果索引不存在，默认为第一个
    });

    // 通用获取消息函数
    const fetchMessages = async (url, targetArray) => {
      get(
        url, {},
        (message) => {
          console.log(message.data);
          targetArray.value = message.data.Messages || [];
          total.value[currentIndex.value] = message.data.Total;
        },
        () => {
          store.clearAccount();
        }
      );
    };

    // 点击切换时调用
    const handleValueChange = (newValue) => {
      //到时候将pagesize和currentpage的逻辑加进来
      value.value = newValue;
      if (newValue === '点赞信息') {
        fetchMessages("/message/like_msg", likeMessages);
      } else if (newValue === '提问信息') {
        fetchMessages("/message/question_msg", questionBoxMessages);
      } else if (newValue === '回复信息') {
        fetchMessages("/message/reply_msg", replyMessages);
      } else if (newValue === '提问箱信息') {
        fetchMessages("/message/box_msg", boxMessages);
      }
    };

    const formattedMessages = computed(() => {
      const sortMessages = (messages) =>
        messages
          .slice() // 创建数组副本，避免影响原始数据
          .sort((a, b) => {
            // 按未读优先排序
            if (!a.is_read && b.is_read) return -1;
            if (a.is_read && !b.is_read) return 1;
            return 0; // 如果都未读或已读，保持原顺序
          })
          .map((item) => ({
            content: `${item.sender_name} ${getMessageContent(item)} ----- ${item.tim}`,
            isRead: item.is_read,
            id: item.id,
          }));

      // 根据当前选项格式化对应消息并排序
      if (value.value === '点赞信息') {
        return sortMessages(likeMessages.value);
      } else if (value.value === '提问信息') {
        return sortMessages(questionBoxMessages.value);
      } else if (value.value === '回复信息') {
        return sortMessages(replyMessages.value);
      } else if (value.value === '提问箱信息') {
        return sortMessages(boxMessages.value);
      }
      return [];
    });

    // 动态返回不同类型的消息内容
    const getMessageContent = (item) => {
      if (value.value === '点赞信息') return '点赞了你';
      if (value.value === '提问信息') return `收到一个新提问：${item.tex}`;
      if (value.value === '回复信息') return `回复了你的消息：${item.tex}`;
      if (value.value === '提问箱信息') return '关注了你的提问箱';
      return '';
    };



    const handlePageChange = (page) => {
      currentPage.value[currentIndex.value] = page;
      handleValueChange(value.value);//刷新下一页/上一页数据
    };

    onMounted(() => {
      fetchMessages("/message/like_msg", likeMessages);
    });


    const markAsRead = async (id) => {
      post(
        "/message/mark_read",
        {},
        (message) => {
          console.log(`Message ${id} marked as read.`);
          handleValueChange(value.value);//点击标记已读后重新刷新这一页数据
        },
        () => {
          console.error("Failed to mark message as read.");
        }
      );
    };


    const router = useRouter(); // 使用 Vue Router 进行导航

    const handleClick = () => {
      //需要添加跳转到的界面的相关标识符，比如个人界面就是用户id
      if (value.value === '点赞信息' || value.value === '提问箱信息') {
        router.push(`/person`); // 跳转到 /person
      } else if (value.value === '提问信息') {
        router.push(`/question`); // 跳转到 /question
      } else if (value.value === '回复信息') {
        router.push(`/comment`); // 跳转到 /comment
      } else {
        console.warn('无法跳转，未定义的消息类型');
      }
    };


    return {
      value,
      options,
      formattedMessages, handleValueChange,
      handlePageChange, pageSize, currentPage, total,
      currentIndex,
      markAsRead,
      handleClick,//点击跳转
    };
  },
};
</script>

<style scoped>
.message-container {
  padding: 1%;
  height: 73%;
  overflow-y: auto;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.message-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: none;
  transition: box-shadow 0.3s;
}
.message-card.unread {
  background-color: #f5f5f5; /* 未读消息背景色 */
  border-left: 4px solid #409eff; /* 蓝色边框 */
}
.message-card:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.pagination {
  height: 5%;
  display: flex;
  justify-content: center;
}
</style>
